package newx.com.loader
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	import newx.BaseObject;
	import newx.utils.debug.IO;
		
	/**
	 * xml加载小工具
	 * @author riki(王俊)	2009/5/4
	 * 
	 */	
	public class NewXmlUtil extends BaseObject
	{
		public function NewXmlUtil()
		{
			super();
		}
		
		/**
		 * 加载外部xml文件
		 * 通过回调事件的e.target.data 取出xml
		 * @param url			：文件地址
		 * @param onComplete	：加载完成后的回调函数
		 * @param onComplete	：回调宿主
		 */		
		public static function xmlLoader(url:String,target:EventDispatcher):void
		{
			IO.traceLog("xmlLoader:",url);
			var tXmlLoader:NewXmlUtil	=	new NewXmlUtil();			
			tXmlLoader.StartLoad(url,target)
		}
		
		private function StartLoad(url:String,target:EventDispatcher):void
		{			
			this.HandleProperties("target",target);
			
			var myXML	:XML 		= new XML();
			var XML_URL	:String 	= url;
			var myXMLURL:URLRequest = new URLRequest(XML_URL);
			var myLoader:URLLoader 	= new URLLoader();
			
			myLoader.dataFormat		= URLLoaderDataFormat.TEXT;
			
			myLoader.addEventListener(Event.COMPLETE,onComplete,false,0,true);
			
			myLoader.addEventListener(IOErrorEvent.IO_ERROR,onIOError,false,0,true);
		
			myLoader.addEventListener(ProgressEvent.PROGRESS,onLoad);
			
			myLoader.load(myXMLURL);
			
//			try
//			{
//				myLoader.load(myXMLURL);
//			}
//			catch(e:*)
//			{
//				IO.traceLog("NewXmlUtil::onIOError:",e.text);
//			
//				if(target != null)
//				{
//					target.dispatchEvent(new XmlLoadEvent(XmlLoadEvent.LOAD_FILEERROR,null,this));
//					this.HandleProperties("target",null);
//				}
//			}
			
		}
		
		private function onLoad(e:ProgressEvent):void		
		{
			IO.traceLog("xmlLoading:",e.bytesLoaded,e.bytesTotal,Number(100*e.bytesLoaded/e.bytesTotal).toFixed(2)+"%");
		}
		
		private function onComplete(e:Event):void		
		{
			IO.traceLog("xmlLoadOver!");
			if(CheckProperties("target"))
			{
				var target:EventDispatcher	=	GetProperties("target")
				DeleteProperties("target")
				target.dispatchEvent(new XmlLoadEvent(XmlLoadEvent.LOAD_COMPLETE,XML(e.target.data),this));
			}			
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			IO.traceLog("NewXmlUtil::onIOError:",e.text);
			
			var target:EventDispatcher	=	GetProperties("target");
			
			if(target != null)
			{			
				target.dispatchEvent(new XmlLoadEvent(XmlLoadEvent.LOAD_FILEERROR,null,this));
				this.HandleProperties("target",null);
			}
		}
	}
}